package com.example.answer_staff;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.answer_staff.api.ApiManager;
import com.gaosai.staff.domain.MessageResult;
import com.gaosai.staff.utils.LogUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class AnswerActivity  extends Activity{
	private String application_list;
	//控制问题的个数的for循环
	private JSONArray quiz_question;
	//控制答案个数的for循环
	private LinearLayout answer_lineraylayout_main;
	private ArrayList<String> quiz_question_parse_lists;
	private String Subject;
	private String briefContent;
	private TextView Quiz_Subject;
	private TextView  Quiz_briefContent;
	private ArrayList<String> quiz_question_question_answers_item_lists;
	private ArrayList<String> question_title_lists;
	private ImageView answer_back_regist;
	private Button activity_answer_bt;
	private ArrayList<String> list_checked_string;
	private ArrayList<String> question_id_lists;
	private String unique_id;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.answer);
		setupView();
		geographicallayout();
		setListeners();
	}
	private void setListeners() {
		answer_back_regist.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();				
			}
		});
		activity_answer_bt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				submit();
			}
		});
	}
	protected void submit() {
		String list_Checked_str_final = list_checked_string.toString();
		Log.i("1111", "list_Checked_str_final是"+list_Checked_str_final);
		String list_checked_subString = list_Checked_str_final.substring(list_Checked_str_final.indexOf("[")+1,list_Checked_str_final.lastIndexOf("]"));
		Log.i("1111", "list_checked_subString是"+list_checked_subString);
		String question_answer_str_final = SpiltList(list_checked_subString);

		ApiManager.getInstance().Answersubmit(AnswerActivity.this, unique_id, question_answer_str_final,new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
			}

			@Override
			public void onFinish() {
				super.onFinish();
			}
			@Override
			public void onStart() {
				super.onStart();
			}
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				//登陆成功以后就将密码存入sharedPreference里边；
				String result = new String(arg2) ;
				LogUtil.e("login result", result) ;
				MessageResult messageResult = MessageResult.prase(result);
				if(0==messageResult.getCode()){
					startActivity(new Intent(AnswerActivity.this,AnswerConfirmActivity.class));
				}else{
					Toast.makeText(AnswerActivity.this, messageResult.getMsg(), 0).show() ;
				}
			}
		}) ;
	}
	private String SpiltList(String list_checked_subString) {
		StringBuilder sb=new StringBuilder();
		String[] question_list_spilt = list_checked_subString.split(",");
		for(int i=0;i<question_list_spilt.length;i++){
			//选出的答案：
			String string_spilt = question_list_spilt[i];
			//找出问题的id  question_id_lists.get(i)；
			sb.append(question_id_lists.get(i)).append("@@").append(string_spilt.trim()).append("&&");
		}
		sb.deleteCharAt(sb.length()-1);
		String question_answer_str = sb.deleteCharAt(sb.length()-1).toString();
		Log.i("1111", "question_answer_str是"+question_answer_str);
		return question_answer_str;
	}

	private ArrayList<String> ParseItem(String str) {
		//加到list里边要注意要清除以前的。
		quiz_question_question_answers_item_lists.clear() ;
		JSONObject jsonObject=null;
		try {
			jsonObject = new JSONObject( str);
			JSONObject quiz_question_question = jsonObject.getJSONObject("question");
			JSONArray quiz_question_question_answers = quiz_question_question.getJSONArray("answers");
			// 循环遍历answers
			for(int i=0;i<quiz_question_question_answers.length();i++){
				JSONObject quiz_question_question_answers_item = quiz_question_question_answers.getJSONObject(i);
				quiz_question_question_answers_item_lists.add((quiz_question_question_answers_item).toString());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return quiz_question_question_answers_item_lists;
	}
	private void geographicallayout() {
		answer_lineraylayout_main=(LinearLayout) this.findViewById(R.id.answer_lineraylayout_main);
		answer_lineraylayout_main.removeAllViews();
		for( int  i=0;i<quiz_question.length();i++){
			LinearLayout Textview_linearlayout=(LinearLayout) LayoutInflater.from(this).inflate(R.layout.answer_textview_dynamic, answer_lineraylayout_main,false);
			TextView tv_question_title = (TextView)Textview_linearlayout.findViewById(R.id.answer_question_title_quiz);
			tv_question_title.setText(question_title_lists.get(i));
			//每一个问题的question的id
			//得到的是0，1 ，2 ，3 ，4
			String quiz_question_item_title = quiz_question_parse_lists.get(i);
			//得到的是0后者1等的众多回答。
			ArrayList<String> answers_item_lists = ParseItem(quiz_question_item_title);
			//要显示每一个问题的abcd 4个答案。
			RadioGroup radioGroup = (RadioGroup)Textview_linearlayout.findViewById(R.id.radioGroup);
			radioGroup.removeAllViews();
			for(int j=0;j<answers_item_lists.size();j++){
				String answer_final = answers_item_lists.get(j);
				//将这个值显示出来在textview里边
				String[] answer_item_string=jsonAnswer(answer_final);
				//如果checkbox已经选中的话，就将textview的值存到sharedpreference里边。
				RadioButton radioBUtton = new RadioButton(AnswerActivity.this) ;
				radioGroup.addView(radioBUtton);
				Log.i("1111", "	After....radioGroup.getChildCount()是"+radioGroup.getChildCount());
					SelectedRadioButton(radioBUtton,answer_item_string[1],j);
				radioBUtton.setText(answer_item_string[0]);
			}
			Log.i("1111", "	wan....radioGroup.getChildCount()是"+radioGroup.getChildCount());
			answer_lineraylayout_main.addView(Textview_linearlayout);
		}	
	}
		private void SelectedRadioButton(final RadioButton radioButton,	final String id, final int j) {
			radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(!isChecked){
						list_checked_string.remove(id);
					}else{
						list_checked_string.add(id.trim());
					}
					Log.i("1111", "list_checked_string是"+list_checked_string.toString());
				}
			});
		}
	//for循环里边的answer_final解析
	private String[] jsonAnswer(String answer_final) {
		JSONObject jsonObject=null;
		String []answer_item=new String[2];
		try {
			jsonObject = new JSONObject( answer_final);
			String answer_item_answer = jsonObject.getString("answer");
			String answer_item_id = jsonObject.getString("id");
			answer_item[0]=answer_item_answer;
			answer_item[1]=answer_item_id;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return answer_item;

	}

	private void setupView() {
		list_checked_string=new ArrayList<String>();
		activity_answer_bt=(Button)findViewById(R.id.activity_answer_bt);
		answer_back_regist=(ImageView)findViewById(R.id.answer_back_regist);
		question_title_lists=new ArrayList<String>();
		Quiz_Subject=(TextView)findViewById(R.id.answer_subject_quiz);
		Quiz_briefContent = (TextView)findViewById(R.id.answer_brief_content_quiz);
		question_id_lists=new ArrayList<String>();
		quiz_question_question_answers_item_lists=new ArrayList<String>();
		quiz_question_parse_lists=new ArrayList<String>();
		application_list=getIntent().getStringExtra("application_list");
		Log.i("eee", "application_list_quiz是"+application_list);
		jsonParse(application_list);
		Log.i("eee", Subject);
		Log.i("eee", "Quiz_Subject是"+Quiz_Subject);
		Log.i("eee", "Quiz_briefContent是"+Quiz_briefContent);
		Quiz_Subject.setText(Subject);

		Quiz_briefContent.setText(briefContent);
	}

	private void jsonParse(String json) {
		JSONObject jsonObject=null;
		try {
			jsonObject = new JSONObject( json);
			Subject=jsonObject.getString("subject");
			Log.i("eee", "解析的subject是"+Subject);
			briefContent=jsonObject.getString("briefContent");
			unique_id=jsonObject.getString("id");
			quiz_question=jsonObject.getJSONArray("quiz_question");
			for(int i=0;i<quiz_question.length();i++){
				JSONObject quiz_question_parse = quiz_question.getJSONObject(i);
				//得到的是0 1 2 3 4等等。
				quiz_question_parse_lists.add((quiz_question_parse).toString());
				JSONObject question = quiz_question_parse.getJSONObject(("question"));
				String question_id = question.getString("id");
				String question_title = question.getString("question_title");
				question_title_lists.add(question_title);
				question_id_lists.add(question_id);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
